package com.hs.srm.admin.modules.material.controller;

import java.util.*;
import java.text.SimpleDateFormat;

import com.hs.srm.admin.modules.material.entity.MaterialEntity;
import com.hs.srm.admin.modules.material.entity.MaterialFactoryEntity;
import com.hs.srm.admin.modules.material.service.MaterialFactoryService;
import com.hs.srm.admin.modules.material.service.MaterialService;
import com.hs.srm.admin.modules.requisition.controller.ProPurchRequetSapTask;
import com.sap.conn.jco.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author socik
 * @date 2019/5/17 8:11
 * @email socik@qq.com
 */
@Component("materialSapTask")
public class MaterialSapTask {
	/**
	 * @Description: 定义sap字段数组
	 */
	String[] material = {"MATNR", "ERNAM", "AENAM", "VPSTA", "VPSTA", "MTART", "AENAM", "BISMT", "MEINS", "BSTME",
			"ATTYP"};
	/**
	 * @Description: 定义物料工厂表数组
	 */
	String[] materialFactory = {"MATNR", "MMSTA", "MMSTD", "WERKS", "LGPRO", "EKGRP", "PSTAT", "LVORM"};
	Logger logger = LoggerFactory.getLogger(ProPurchRequetSapTask.class);
	@Autowired
	private MaterialService materialServiceImpl;
	@Autowired
	private MaterialFactoryService materialFactoryServiceImpl;

	/**
	 * @Description SAP物料接口4001-4099
	 * @Param []
	 * @Return void
	 * @Author socik
	 * @Date 2019/5/17 8:17
	 */
	public void materialSapTask1() {
		this.postMateral("4001", "4099");
	}

	/**
	 * @Description SAP物料接口1001-1099
	 * @Param []
	 * @Return void
	 * @Author socik
	 * @Date 2019/5/17 8:17
	 */
	public void materialSapTask() {
		this.postMateral("1001", "1099");
	}

	/**
	 * 传递物料数据
	 *
	 * @param minGroup 物料组最小值
	 * @param maxGroup 物料组最大值
	 */
	private void postMateral(String minGroup, String maxGroup) {
		this.logger.debug("物料接口开始启动!");
		// 定义物料Map
		List<Map<String, Object>> materialMap = new ArrayList<>();
		List<Map<String, Object>> materialFactoryMap = new ArrayList<>();
		boolean flg = false;
		JCoDestination destination = null;
		JCoFunction function = null;
		JCoParameterList tables = null;
		JCoParameterList importList = null;
		try {
			destination = JCoDestinationManager.getDestination("IDOC_AFS");
			function = destination.getRepository().getFunction("ZEXCHANGE_MAT");
			tables = function.getTableParameterList();
			importList = function.getImportParameterList();
		} catch(JCoException e) {
			e.printStackTrace();
			throw new RuntimeException("数据传递出错！");
		}
		// 获取Sap导入参数接口
		JCoStructure value_desc = importList.getStructure("I_MARA");
		// 传入物料组数据
		value_desc.setValue("MATKL_B", minGroup);
		value_desc.setValue("MATKL_E", maxGroup);
		try {
			function.execute(destination);
		} catch(JCoException e) {
			e.printStackTrace();
		}
		// 得到Sap返回表
		JCoTable returnTable = tables.getTable("T_MARA");
		// 物料描述表
		JCoTable returnTable1 = tables.getTable("T_MAKT");
		// 物料工厂表
		JCoTable returnTable2 = tables.getTable("T_MARC");
		if(returnTable.getNumRows() > 0 && returnTable1.getNumRows() > 0) {
			// 循环Sap返回表数据
			for(int x = 0; x < returnTable.getNumRows(); x++) {
				returnTable.setRow(x);
				Map<String, Object> map = new HashMap<>();
				for(int s = 0; s < material.length; s++) {
					map.put(material[s], returnTable.getValue(this.material[s]));
				}
				materialMap.add(map);
			}
			for(int g = 0; g < materialMap.size(); g++) {
				for(int j = 0; j < returnTable1.getNumRows(); j++) {
					returnTable1.setRow(j);
					// 当两张表物料号一样的时候插入数据,SPRAS==1,中文物料描述
					if(returnTable1.getValue("MATNR").equals(materialMap.get(g).get("MATNR"))&& returnTable1.getValue("SPRAS").equals("1")) {
						// 循环放入Map字段数据
						materialMap.get(g).put("MAKTX", returnTable1.getValue("MAKTX"));
					}
				}
				String matnr = (String)materialMap.get(g).get("MATNR");
				MaterialEntity materialEntity = this.materialServiceImpl.selectMaterialByCode(matnr.replaceAll("^(0+)",""));
				if(materialEntity == null) {
					try {
						flg = this.insertMateral(materialMap.get(g));
					} catch(Exception e) {
						e.printStackTrace();
					}
					if(flg) {
						logger.debug("物料主数据同步成功!物料号为:" + materialMap.get(g).get("MATNR"));
					} else {
						logger.debug("物料主数据同步失败!");
					}
				}
			}
			if(returnTable2.getNumRows() > 0) {
				// 循环取出工厂数据
				for(int v = 0; v < returnTable2.getNumRows(); v++) {
					returnTable2.setRow(v);
					Map<String, Object> map = new HashMap<String, Object>();
					for(int i = 0; i < materialFactory.length; i++) {
						map.put(this.materialFactory[i], returnTable2.getValue(this.materialFactory[i]));
					}
					materialFactoryMap.add(map);
				}
				for(int c = 0; c < materialFactoryMap.size(); c++) {
					String matnr = (String)materialFactoryMap.get(c).get("MATNR");
					MaterialFactoryEntity materialFactoryEntiy = this.materialFactoryServiceImpl
							.selectMaterialFactoryByCode(matnr.replaceAll("^(0+)", ""),
									(String)materialFactoryMap.get(c).get("WERKS"));
					if(materialFactoryEntiy == null) {
						try {
							flg = this.insertMateralFactory(materialFactoryMap.get(c));
						} catch(Exception e) {
							e.printStackTrace();
						}
						if(flg) {
							logger.debug("物料工厂同步成功!");
						} else {
							logger.debug("物料工厂同步失败!");
						}
					}
				}
			}
		}
	}

	/**
	 * @Description 插入物料主数据
	 * @Param [map]
	 * @Return boolean
	 * @Author socik
	 * @Date 2019/5/18 7:45
	 */
	private boolean insertMateral(Map<String, Object> map) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		MaterialEntity materialEntity = new MaterialEntity();
		// 物料号
		materialEntity.setMaterialCode(((String)map.get("MATNR")).replaceAll("^(0+)", ""));
		// 物料描述
		materialEntity.setMaterialDesc((String)map.get("MAKTX"));
		// 创建日期
		materialEntity.setCreationDate((Date)(map.get("ERSDA")));
		// 创建人
		materialEntity.setCreatedBy((String)map.get("ERNAM"));
		// 上次更改的日期
		materialEntity.setLastUpdateDate((Date)(map.get("LAEDA")));
		// 对象更改人员
		materialEntity.setLastUpdatedBy((String)map.get("AENAM"));
		// 维护全部物料状态
		materialEntity.setMaterialStatus((String)map.get("VPSTA"));
		// 物料类型
		materialEntity.setMaterialType((String)map.get("MTART"));
		// 行业领域
		materialEntity.setIndustrySector((String)map.get("AENAM"));
		// 物料组
		materialEntity.setMaterialGroup((String)map.get("MATKL"));
		// 普通项目类别组
		materialEntity.setNormalItemCategory((String)map.get("AENAM"));
		// 旧物料号
		materialEntity.setOldMaterialCode((String)map.get("BISMT"));
		// 基本计量单位
		materialEntity.setBasicUnit((String)map.get("MEINS"));
		// 采购订单的计量单位
		materialEntity.setPoUnit((String)map.get("BSTME"));
		// 货源
		materialEntity.setGoodsSource((String)map.get("BWSCL"));
		// 开始生效日期
		materialEntity.setEffectiveDate((Date)(map.get("DATAB")));
		// 删除日期
		materialEntity.setDeletedDate((Date)(map.get("LIQDT")));
		// 物料类别
		materialEntity.setMaterialCategory((String)map.get("ATTYP"));

		boolean flg = this.materialServiceImpl.insertMaterial(materialEntity);
		return flg;
	}

	/**
	 * @Description 插入物料工厂数据
	 * @Param [map]
	 * @Return boolean
	 * @Author socik
	 * @Date 2019/5/18 7:45
	 */
	private boolean insertMateralFactory(Map<String, Object> map) throws Exception {
		MaterialFactoryEntity materialFactoryEntity = new MaterialFactoryEntity();
		// 物料号
		materialFactoryEntity.setMaterialCode(((String)map.get("MATNR")).replaceAll("^(0+)", ""));
		// 跨工厂物料状态
		materialFactoryEntity.setCrossMaterialStatus((String)map.get("MMSTA"));
		// 从跨工厂物料状态有效起的日期
		materialFactoryEntity.setBeginDate((Date)map.get("MMSTD"));
		// 工厂
		materialFactoryEntity.setWerks((String)map.get("WERKS"));
		// 库存地点
		materialFactoryEntity.setStorageLocation((String)map.get("LGPRO"));
		// 采购组
		materialFactoryEntity.setPurchaseGroup((String)map.get("EKGRP"));
		// 维护状态
		materialFactoryEntity.setStatus((String)map.get("PSTAT"));
		// 在客户级标记要删除的物料
		materialFactoryEntity.setDeletedFlag((String)map.get("LVORM"));

		boolean flg = this.materialFactoryServiceImpl.insertMaterial(materialFactoryEntity);
		return flg;
	}

}
